package com.doodle.common.drawable;

import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;

public class ClipDrawable extends DrawableWrapper {
	
	private float mLeftRatio;
	private float mTopRatio;
	private float mRightRatio;
	private float mBottomRatio;
	
	private float mGlobalRatio = 1.0f;
	
	private int mLeft;
	private int mTop;
	private int mRight;
	private int mBottom;

	public ClipDrawable(Drawable drawable) {
		super(drawable);
	}
	
	public ClipDrawable(Drawable drawable, float l, float t, float r, float b) {
		super(drawable);
		mLeftRatio = l;
		mTopRatio = t;
		mRightRatio = r;
		mBottomRatio = b;
	}
	
	@Override
    public void setBounds(int left, int top, int right, int bottom) {
        super.setBounds(left, top, right, bottom);
        updateClip(left, top, right, bottom);
    }
	
	@Override
	public void draw(Canvas canvas) {
		Rect bounds = getBounds();
    	int count = canvas.save(Canvas.CLIP_SAVE_FLAG);
    	canvas.clipRect(bounds.left + mLeft, bounds.top + mTop, bounds.right - mRight, bounds.bottom - mBottom);
        super.draw(canvas);
        canvas.restoreToCount(count);
	}
	
	public void updateClip(int l, int t, int r, int b) {
		int width = r - l;
		int height = b - t;
		mLeft = Math.round(mLeftRatio * mGlobalRatio * width);
		mTop = Math.round(mTopRatio * mGlobalRatio * height);
		mRight = Math.round(mRightRatio * mGlobalRatio * width);
		mBottom = Math.round(mBottomRatio * mGlobalRatio * height);
	}
	
	public void setGlobalRatio(float globalRatio) {
		mGlobalRatio = globalRatio;
		Rect bounds = getBounds();
		updateClip(bounds.left, bounds.top, bounds.right, bounds.bottom);
		invalidateSelf();
	}
	
	public float getGlobalRatio() {
		return mGlobalRatio;
	}
}
